import React, {Component} from 'react'
import {View, Text, ScrollView, TextInput, TouchableOpacity, Alert} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import styles from '../../config/styles'
import StudentsSelector from '../common/students_selector'
import FormatDate from '../../helpers/timeFormat'
import DateTimePicker from 'react-native-modal-datetime-picker'
import {PostCreateHomeworkAPi} from '../../config/api'

class newHomeworkWithText extends Component {
    static navigationOptions = ({ navigation }) => {
        const params = navigation.state.params
        if (params != undefined) {
            const _headerRight = (<TouchableOpacity
                                        style={{paddingRight: 5}}
                                        onPress={params.submit}
                                    >
                                        <Text style={[styles.header_font]}>
                                            发布
                                        </Text>   
                                    </TouchableOpacity>
                                )
            return {
                headerRight: _headerRight
            }
        }
    } 
    
    constructor (props) {
        super(props);
        this.state = {
            objectForSubmit: {
                lesson_teacher_id: null,
                title: "",
                needReply: true,
                needScore: true,
                description: "",
                chapter_id: null,
                students: [],
                attachments: [],
                collect_date: null,
                tasks: [],
                include_tasks: true
            },
            classrooms: [],
            gradeName: '',
            gradeId: null,
            pickingTime: false,
            refresh: props.navigation.state.params.refresh
        }
    }

    componentDidMount () {
        this.props.navigation.setParams({
            submit: () => {
                const {objectForSubmit} = this.state
                if (objectForSubmit.title == "") {
                    Toast.show('请填写标题')
                    return
                } else if (objectForSubmit.students.length == 0) {
                    Toast.show('至少选择一个学生')
                    return
                } else if (objectForSubmit.tasks.length == 0) {
                    Toast.show('至少添加一篇课文')
                    return
                }
                PostCreateHomeworkAPi(objectForSubmit).then((data) => {
                    if (data.status == 201) {
                        Toast.show('创建成功')
                        this.state.refresh()
                        this.props.navigation.goBack()
                    }
                })
            }
        })
    }

    //设置标题
    setTitle = (txt) => {
        const _objectForSubmit = this.state.objectForSubmit
        _objectForSubmit.title = txt
        this.setState({objectForSubmit: _objectForSubmit})
    }

    //跳转到选择年级的页面
    selectGrade = () => {
        const {navigation} = this.props
        const onComplete = (grade) => {
            this.setState({classrooms: grade.classrooms, gradeName: grade.name, gradeId: grade.id})
        }
        navigation.navigate('grade_selector', {onComplete: onComplete})
    }

    //跳转到选择课文的页面
    selectTask = (task=null) => {
        if (this.state.gradeId == null) {
            Toast.show('请先选择年级')
            return
        }
        const {navigation} = this.props
        const onComplete = (returnTask) => {
            if (task == null) {
                this.state.objectForSubmit.tasks.push(returnTask)
            } else {
                Object.keys(returnTask).forEach((k) => {
                    task[k] = returnTask[k]
                })
            }
            this.setState({objectForSubmit: this.state.objectForSubmit})
        }
        navigation.navigate('add_text_book', {onComplete: onComplete, task: task, grade_id: this.state.gradeId})
    }

    //添加描述
    addDescribe = () => {
        const {navigation} = this.props
        const {objectForSubmit} = this.state
        const onComplete = (description, attachments) => {
            objectForSubmit.description = description
            objectForSubmit.attachments = attachments
            this.setState({objectForSubmit: objectForSubmit})
        }
        navigation.navigate('add_homework_describe', {
            onComplete: onComplete,
            description: objectForSubmit.description,
            attachments: objectForSubmit.attachments
        })
    }

    //打开时间选择框
    selectCollectDate = (date) => {
        this.state.objectForSubmit.collect_date = FormatDate(date)
        this.setState({objectForSubmit: this.state.objectForSubmit, pickingTime: false})
    }

    //将选择学生的函数传给子组件
    studentsSelect = (newSelectedStudents) => {
        this.state.objectForSubmit.students = newSelectedStudents
        this.setState({objectForSubmit: this.state.objectForSubmit})
    }

    //删除一个task
    removeTask = (task) => {
        Alert.alert('删除确认', '确认删除该条task吗？', [
            {
                text: '取消',
                onPress: () => {}
            },
            {
                text: '确认', 
                onPress: () => {
                    const {tasks} = this.state.objectForSubmit
                    const _tasks = tasks.filter((t) => {
                        return t.id != task.id
                    })
                    this.state.objectForSubmit.tasks = _tasks
                    this.setState({})
                }
            }
        ])
        
    }

    //课文模板
    taskTemplate = (task, index) => {
        return(
            <TouchableOpacity
                style={[styles.background_light_grey, {margin: 10, padding: 10, flexDirection: 'row'}]}
                key={index}
                onPress={() => this.selectTask(task)}
            >
                <View style={{flex: 1}}>
                    <View style={{paddingBottom: 8, flexDirection: 'row'}}>
                        <Text style={{flex: 1}} >{task.bookName}</Text>
                        <TouchableOpacity 
                            onPress={() => {this.removeTask(task)}}
                            style={{position: 'relative', left: 5, bottom: 5}}>
                            <Icon name={'md-close'} size={20} color={'red'} />
                        </TouchableOpacity>
                    </View>
                    <Text style={{paddingBottom: 8}}>{task.chapterName}</Text>
                    <Text>{task.sectionName}</Text>
                </View>
                <View>
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Icon  name={'ios-arrow-forward'} size={18} color={'#707070'} />
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    render () {
        const {gradeName, classrooms, objectForSubmit} = this.state
        return (
            <ScrollView style={styles.main_body}>
                 <DateTimePicker
                    isVisible={this.state.pickingTime}
                    onConfirm={(date) => {this.selectCollectDate(date)}}
                    onCancel={() => this.setState({pickingTime: false})}
                    date={objectForSubmit.collect_date ? new Date(objectForSubmit.collect_date) : new Date()}
                    cancelTextIOS={'取消'}
                    confirmTextIOS={'确定'}
                    titleIOS={'选择日期'}
                />
                <View style={styles.view_module_container}>
                    <View style={styles.text_content_container}>
                        <TextInput
                            style={{padding: 0, flex: 1}}
                            placeholder={'请输入作业标题'}
                            onChangeText={(txt) => this.setTitle(txt)}
                        />
                    </View>

                    <TouchableOpacity 
                        style={[styles.text_content_container, {flexDirection: 'row',justifyContent: 'flex-start', alignItems: 'center'}]}
                        onPress={this.addDescribe}
                    >
                        <Text style={[styles.text_black, {flex: 1}]}>
                            作业描述:
                        </Text>
                        <Text 
                            numberOfLines={1}
                            style={[styles.text_black, {paddingRight: 3}]}
                        >
                            {objectForSubmit.description}
                        </Text>
                        <Icon name={'ios-arrow-forward'} size={18} color={'#707070'} />
                    </TouchableOpacity>

                    <TouchableOpacity 
                        style={[styles.text_content_container, {flexDirection: 'row',justifyContent: 'flex-start', alignItems: 'center'}]}
                        onPress={this.selectGrade}
                    >
                        <Text style={[styles.text_black, {flex: 1}]}>
                            选择年级:
                        </Text>
                        <Text style={[styles.text_black, {paddingRight: 3}]}>
                            {gradeName}
                        </Text>
                        <Icon name={'ios-arrow-forward'} size={18} color={'#707070'} />
                    </TouchableOpacity>

                    <TouchableOpacity 
                        style={[styles.text_content_container, {flexDirection: 'row',justifyContent: 'flex-start', alignItems: 'center'}]}
                        onPress={() => {this.setState({pickingTime: true})}}
                    >
                        <Text style={[styles.text_gray, {flex: 1}]}>
                            截止时间:
                        </Text>
                        <Text style={[styles.text_black, {paddingRight: 3}]}>
                            {objectForSubmit.collect_date}
                        </Text>
                        <Icon name={'ios-arrow-forward'} size={18} color={'#707070'} />
                    </TouchableOpacity>
                </View>

                <View style={[styles.view_module_container, {marginTop: 10}]}>
                    <Text style={{marginLeft:15}}>选择作业范围</Text>
                    {
                        this.state.classrooms && this.state.classrooms.length > 0 ? 
                            ( <StudentsSelector
                                classrooms={classrooms}
                                studentsSelect={this.studentsSelect}
                                selectedStudents={this.state.objectForSubmit.students}
                            />) : null
                    }
                </View>

                <View style={[styles.view_module_container, {marginTop: 10}]}>
                    <Text style={{marginLeft:15}}>设置作业</Text>
                    {
                        objectForSubmit.tasks.map((t, index) => {
                            return this.taskTemplate(t, index)
                        })
                    }
                    <TouchableOpacity
                        style={[styles.as_large_button, styles.background_blue, {margin: 15}]}
                        onPress={() => this.selectTask()}
                    >
                        <Text style={styles.text_white}>+ 添加作文作业</Text>
                    </TouchableOpacity>
                </View>
            </ScrollView>
        )
    }
}

export default newHomeworkWithText